<template>
    <div class="app-container">
        <public-search @on-query="handleQuery" @on-reset="resetQuery">
            <el-form :model="queryParams" ref="queryForm" size="small" label-width="78px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="作业项目" prop="projectName">
                            <el-input size="small" v-model="queryParams.projectName" placeholder="请输入作业项目" clearable
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="井号" prop="wellNo">
                            <el-input size="small" v-model="queryParams.wellNo" placeholder="请输入井号" clearable
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="井别" prop="wellType">
                            <el-input size="small" v-model="queryParams.wellType" placeholder="请输入井别" clearable
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="开工日期" prop="workStartTime">
                            <el-date-picker size="small" v-model="queryParams.workStartTime" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </public-search>

        <public-table>
            <template slot="operate">
                <div>
                    <el-button type="primary" @click="handleExport" v-if="pageType === 'ledger'">导出</el-button>
                    <el-button type="primary" @click="handleAdd" v-if="pageType === ''">新增</el-button>
                </div>
            </template>
            <template slot="table">
                <el-table v-loading="loading" border :data="dataList">
                    <el-table-column label="序号" align="center" width="50px" type="index" />
                    <el-table-column label="施工单位" prop="constructionOrganization" width="150" />
                    <el-table-column label="井号" prop="wellNo" width="120" />
                    <el-table-column label="井别" prop="wellType" width="100" />
                    <el-table-column label="作业项目" prop="projectName" width="150">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" :open-delay="500" width="400" trigger="hover">
                                <div>
                                    <div v-for="(str, index) in str2List(scope.row.projectName)" :key="index">
                                        {{ index + 1 }}、{{ str }}
                                    </div>
                                </div>
                                <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.projectName }}
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="风险因素" prop="riskFactor" min-width="100">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" :open-delay="500" width="800" trigger="hover">
                                <div>
                                    <div v-for="(str, index) in str2List(scope.row.riskFactor)" :key="index">
                                        {{ index + 1 }}、{{ str }}
                                    </div>
                                </div>
                                <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.riskFactor }}
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="可能导致事故类型" prop="accidentType" min-width="100">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" :open-delay="500" width="400" trigger="hover">
                                <div>
                                    <div v-for="(str, index) in str2List(scope.row.accidentType)" :key="index">
                                        {{ index + 1 }}、{{ str }}
                                    </div>
                                </div>
                                <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.accidentType }}
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="主要管控措施" prop="controlMeasure" min-width="100">
                        <template slot-scope="scope">
                            <el-popover placement="top-start" :open-delay="500" width="800" trigger="hover">
                                <div>
                                    <div v-for="(str, index) in str2List(scope.row.controlMeasure)" :key="index">
                                        {{ index + 1 }}、{{ str }}
                                    </div>
                                </div>
                                <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.controlMeasure }}
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="所在平台" prop="hostPlatform" width="130" />
                    <el-table-column label="开工日期" prop="workStartTime" width="170" />
                    <el-table-column label="填报日期" prop="fillTime" width="170" />
                    <el-table-column label="施工内容（简述）" prop="buildTime" align="center">
                        <el-table-column label="06:00-16:00" prop="buildTimeOne" width="100">
                            <template slot-scope="scope">
                                <el-popover placement="top-start" :open-delay="500" width="400" trigger="hover">
                                    <div>{{ scope.row.buildTimeOne }}</div>
                                    <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.buildTimeOne
                                    }}</div>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="16:00-24:00" prop="buildTimeTwo" width="100">
                            <template slot-scope="scope">
                                <el-popover placement="top-start" :open-delay="500" width="400" trigger="hover">
                                    <div>{{ scope.row.buildTimeTwo }}</div>
                                    <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.buildTimeTwo
                                    }}</div>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="00:00-06:00" prop="buildTimeThree" width="100">
                            <template slot-scope="scope">
                                <el-popover placement="top-start" :open-delay="500" width="400" trigger="hover">
                                    <div>{{ scope.row.buildTimeThree }}</div>
                                    <div class="text-overflow-ellipsis pointer" slot="reference">{{ scope.row.buildTimeThree
                                    }}
                                    </div>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column label="下步工序" prop="nextStep" min-width="100" />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="110"
                        fixed="right">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="handleDetail(scope.row)">详情</el-button>
                            <!-- <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button> -->
                            <el-button size="mini" type="text" @click="handleDelete(scope.row)" v-if="pageType === 'ledger'">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <template slot="pagination">
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </template>
        </public-table>



        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
            <el-form style="width: 90%;margin: 0 auto;" ref="form" :model="form" :rules="rules" label-width="150px">
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="施工单位" prop="constructionOrganization" size="small">
                            <el-input v-model="form.constructionOrganization" placeholder="请输入施工单位" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="责任人" prop="personInCharge" size="small">
                            <el-input v-model="form.personInCharge" placeholder="请输入责任人"
                                :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="井号" prop="wellNo" size="small">
                            <el-input v-model="form.wellNo" placeholder="请输入井号" :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="井别" prop="wellType" size="small">
                            <el-input v-model="form.wellType" placeholder="请输入井别" :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="开工日期" prop="workStartTime" size="small">
                            <el-date-picker type="datetime" v-model="form.workStartTime" placeholder="请选择开工日期"
                                value-format="timestamp" :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所在平台" prop="hostPlatform" size="small">
                            <el-input v-model="form.hostPlatform" placeholder="请输入所在平台" :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="填报日期" prop="fillTime" size="small">
                            <el-input v-model="form.fillTime" placeholder="" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="下步工序" prop="nextStep" size="small">
                            <el-input v-model="form.nextStep" placeholder="" :disabled="openType === 'detail'" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="作业项目" prop="riskFactor" size="small" v-if="openType === 'detail'">
                    <div class="context-area el-input__inner">
                        <div v-for="(str, index) in str2List(form.projectIds)" :key="index">{{ index + 1
                        }}、{{ str }}</div>
                    </div>
                </el-form-item>

                <el-form-item label="作业项目" prop="projectName" size="small" v-else>
                    <el-cascader style="width: 100%" :props="props" :options="projectTree" filterable collapse-tags
                        v-model="form.projectIds" placeholder="请选择作业项目" clearable @change="onSelectProjectChange" />
                </el-form-item>



                <el-form-item label="风险因素" prop="riskFactor" size="small">
                    <div class="context-area el-input__inner">
                        <div v-for="(str, index) in str2List(form.riskFactor)" :key="index">{{ index + 1 }}、{{ str }}</div>
                    </div>
                </el-form-item>

                <el-form-item label="可能导致的事故类型" prop="accidentType" size="small">
                    <div class="context-area el-input__inner">
                        <div v-for="(str, index) in str2List(form.accidentType)" :key="index">{{ index + 1 }}、{{ str }}
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="主要管控措施" prop="controlMeasure" size="small">
                    <div class="context-area el-input__inner">
                        <div v-for="(str, index) in str2List(form.controlMeasure)" :key="index">{{ index + 1 }}、{{ str }}
                        </div>
                    </div>
                </el-form-item>


                <el-divider content-position="center" class="form-divider">施工内容</el-divider>

                <el-form-item label="06:00-16:00" prop="buildTimeOne" size="small">
                    <el-input type="textarea" :rows="3" v-model="form.buildTimeOne" placeholder="请简述施工内容"
                        :disabled="openType === 'detail'" />
                </el-form-item>
                <el-form-item label="16:00-24:00" prop="buildTimeTwo" size="small">
                    <el-input type="textarea" :rows="3" v-model="form.buildTimeTwo" placeholder="请简述施工内容"
                        :disabled="openType === 'detail'" />
                </el-form-item>
                <el-form-item label="00:00-06:00" prop="buildTimeThree" size="small">
                    <el-input type="textarea" :rows="3" v-model="form.buildTimeThree" placeholder="请简述施工内容"
                        :disabled="openType === 'detail'" />
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center;" v-if="openType != 'detail'">
                <el-button @click="cancel" size="small">取 消</el-button>
                <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
            </div>
        </el-dialog>


    </div>
</template>
  
<script>
import Api from '@/api/business/risk/report'
import RiskLibsApi from '@/api/business/risk-libs/index'
import { mapGetters } from 'vuex'
import moment from "moment"
let allRiskLibData = []
const options = {
    page: {
        title: "作业报备",
        name: "RiskPlan"
    },
    row: {
        id: "id",
        title: ""
    },
    form: {
        insertTitle: "新增作业报备",
        updateTitle: "编辑作业报备",
        detailTitle: "查看作业报备",
    }
}

export default {
    name: options.page.name,
    props: {
        pageType: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            dataList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            openType: "",

            // 日期范围
            dateRange: [],

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                wellNo: undefined,
                wellType: undefined,
                projectName: undefined,
                workStartTime: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                wellNo: [
                    { required: true, message: '井号不能为空', trigger: 'blur' }
                ],
                wellType: [
                    { required: true, message: '井别不能为空', trigger: 'blur' }
                ],
                personInCharge: [
                    { required: true, message: '责任人不能为空', trigger: 'blur' }
                ],
                projectName: [
                    { required: true, message: '作业项目不能为空', trigger: 'blur' }
                ],
                workStartTime: [
                    { required: true, message: '开工日期不能为空', trigger: 'blur' }
                ],
            },

            riskLibData: [],

            props: {
                multiple: true,
                label: 'name',
                value: 'id',
            },
            projectTree: [],
        }
    },
    computed: {
        ...mapGetters(["user"])
    },
    created() {
        if (this.pageType === '') {
            this.queryParams.userId = this.user.userId
        }
        this.getList()
        this.queryWorkProjectList()
    },
    methods: {
        str2List(str) {
            try {
                return str ? str.split("|") : []
            } catch (e) {
                return []
            }
        },
        onSelectProjectChange(list) {
            let ids = []
            let names = []
            let accidentTypes = []
            let riskFactors = []
            let controlMeasures = []
            list.forEach(l => {
                const id = l[2]
                const obj = allRiskLibData.find(item => item.id === id)
                ids.push(obj.id)
                names.push(obj.name)
                accidentTypes.push(obj.accidentType)
                riskFactors.push(obj.riskFactor)
                controlMeasures.push(obj.controlMeasure)
            })
            this.form.controlMeasure = controlMeasures.join("|")
            this.form.riskFactor = riskFactors.join("|")
            this.form.accidentType = accidentTypes.join("|")
            this.form.projectName = ids.sort(function (a, b) { return a - b }).join("|")
        },
        /** 查询数据列表 */
        getList() {
            this.loading = true
            Api.query(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                this.dataList = response.data
                this.total = response.total
                this.loading = false
            }
            )
        },

        // 获取作业项目列表
        queryWorkProjectList() {
            RiskLibsApi.all("1").then(data => {
                allRiskLibData = data
                RiskLibsApi.tree("1").then(data => {
                    this.projectTree = data
                })
            })
        },

        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },

        // 表单重置
        reset() {

            this.form = {
                "constructionOrganization": this.user.dept.deptName, //施工单位
                "controlMeasure": "", //主要管控措施
                "wellNo": "", //井号
                "wellType": "", //井别
                "hostPlatform": "", //所在平台
                "projectIds": [], //作业项目
                "projectName": "", //作业项目
                "projectId": "", //作业项目ID
                "workStartTime": "", //开工日期
                "riskFactor": "", //风险因素
                "fillTime": moment().format("YYYY-MM-DD HH:mm:ss"), //填报日期
                "accidentType": "", //可能导致的事故类型
                "nextStep": "", //下步工序
                "buildTimeOne": "", //施工内容1
                "buildTimeTwo": "", //施工内容2
                "buildTimeThree": "", //施工内容3
                "personInCharge": "" //责任人
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },


        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.openType = "create"
            this.title = options.form.insertTitle
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row[options.row.id]
            Api.get(id).then(res => {
                this.form = res.data
                this.form.workStartTime = new Date(res.data.workStartTime).getTime()
                let ids = []
                try {
                    ids = res.data.projectName.split("|")
                } catch (e) {
                    console.error("【projectName】格式错误: ", res.data.projectName)
                }
                this.form.projectIds = ids.map(tId => {
                    const sId = allRiskLibData.find(item => item.id == tId).parentId
                    const fId = allRiskLibData.find(item => item.id == sId).parentId
                    return [fId, sId, tId * 1]
                })
                this.open = true
                this.openType = "update"
                this.title = options.form.updateTitle
            })
        },
        /** 详情按钮操作 */
        handleDetail(row) {
            this.reset()
            const id = row[options.row.id]
            Api.get(id).then(res => {
                this.form = res.data
                this.form.workStartTime = new Date(res.data.workStartTime).getTime()
                let ids = []
                try {
                    ids = res.data.projectName.split("|")
                } catch (e) {
                    console.error("【projectName】格式错误: ", res.data.projectName)
                }
                this.form.projectIds = ids.map(tId => {
                    const obj = allRiskLibData.find(item => item.id == tId)
                    if(obj) return obj.name
                    return tId
                }).join("|")
                this.open = true
                this.openType = "detail"
                this.title = options.form.detailTitle
            })
        },


        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form[options.row.id] != undefined) {
                        Api.update(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        Api.insert(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row[options.row.id]
            this.$modal.confirm('删除不可恢复，是否确定删除？').then(function () {
                return Api.del(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download2(Api.export, { ...this.queryParams })
        }
    }
}
</script>
  
  